package com.bizmda.bizsip.app.client;

import lombok.Getter;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Getter
public class DelayAppServiceClientProxy<T> implements InvocationHandler, Serializable {

    private final Class<T> mapperInterface;
    private final Map<Method, DelayAppServiceClientMethod> methodCache;
    private String bizServiceId;
    private int[] delayMilliseconds;

    public DelayAppServiceClientProxy(Class<T> mapperInterface, String bizServiceId, int[] delayMilliseconds) {
        this.mapperInterface = mapperInterface;
        this.methodCache = new HashMap<>();
        this.bizServiceId = bizServiceId;
        this.delayMilliseconds = delayMilliseconds;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                throw t;
            }
        }
        final DelayAppServiceClientMethod delayAppServiceClientMethod = cachedMapperMethod(method);

        return delayAppServiceClientMethod.execute(args);
    }

    private DelayAppServiceClientMethod cachedMapperMethod(Method method) {
        DelayAppServiceClientMethod delayAppServiceClientMethod = methodCache.get(method);
        if (delayAppServiceClientMethod == null) {
            delayAppServiceClientMethod = new DelayAppServiceClientMethod(method, this);
            methodCache.put(method, delayAppServiceClientMethod);
        }
        return delayAppServiceClientMethod;
    }

}
